﻿using AutoMapper;
using HuaHan.WorkTicket.Domain;
using HuaHan.WorkTicket.Domain.Model;
using HuaHan.WorkTicket.Domain.Repositories;
using HuaHan.WorkTicket.Domain.Repositories.EntityFramework;
using HuaHan.WorkTicket.ServiceContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WorkTicket.Application.Implementation
{
    public class DepartmentServiceImpl : BaseServiceImpl<Department>, IDepartmentService
    {

        #region Private Fields
        private UnitOfWork unitOfWork = new UnitOfWork();
        #endregion

        public DepartmentServiceImpl()
        {
            base.Repository = unitOfWork.DepartmentRepository;
            base.UnitOfWork = this.unitOfWork;
        }


        public override List<Department> GetAll()  
        {
            List<Department> result = base.Repository.GetAll().Where(c => c.IsDeleted == false).OrderByDescending(c => c.CreatedAt).ToList();
            foreach (var item in result)
            {
                item.ChildDepartmentList = this.GetChildDepartment(item.DepartmentID);
            }
            return result;
        }

        private List<Department> GetChildDepartment(Guid parentID)
        {
            List<Department> result = new List<Department>();
            result = base.Repository.GetAll().Where(c => c.IsDeleted == false && c.ParentID == parentID).OrderByDescending(c => c.CreatedAt).ToList();
            return result;
        }


        public bool CheckNameExisted(string name,Guid id)
        {
            var count = base.Repository.GetAll().Where(c => c.Name == name && c.DepartmentID != id).Count();
            if (count > 0)
                return false;
            else
                return true;
        }
    }
}
